<template>
  <div class="app-container flex column">
    <!-- 场所管理-场所分类 -->
    <top-title :content="content" :updateTime="true"></top-title>
    <div class="tree-from-wrap f1 flex m-h-0">
      <div class="left-tree-wrap bg-common-card f1 m-h-0 flex column">
        <!-- 提醒 -->
        <div class="alter flex align-center">
          <img alt="" src="@/assets/imgs/alter_icon.png" />
          <span>当前选择:</span>
          <span v-if="currSelected.id">{{ currSelected.informationName }}</span>
          <span v-if="currSelected.id" @click="onClearSelected">取消选择</span>
        </div>

        <div class="search-group" style="padding: 0 0.1rem 0 0.2rem">
          <div class="input-wrap" style="width: 100%">
            <div class="input-item" style="padding: 0; width: 100%">
              <a-input v-model="value" :maxLength="15" placeholder="请输入分类名称" @pressEnter="onSearch">
                <a-icon slot="prefix" class="search-icon" type="search" />
                <a-button slot="suffix" class="searchBtn" style="margin-right: 0" type="primary" @click="onSearch"
                  >搜索</a-button
                >
              </a-input>
            </div>
          </div>
        </div>

        <div class="tree-wrap f1 m-h-0">
          <a-tree
            :autoExpandParent="autoExpandParent"
            :checkStrictly="checkStrictly"
            :checkedKeys="checkedKeys"
            :expandedKeys="iExpandedKeys"
            :loading="loading"
            :replace-fields="replaceFields"
            :selectedKeys="selectedKeys"
            :treeData="departTree"
            checkable
            multiple
            @check="onSelect"
            @expand="onExpand"
            @select="onSelect"
          >
            <a-icon slot="switcherIcon" type="down" />
            <template #title="{ informationName }">
              <span v-if="informationName.indexOf(value) > -1">
                {{ informationName.substr(0, informationName.indexOf(value)) }}
                <span style="color: #ecf0f1; background: #74b9ff">{{ value }}</span>
                {{ informationName.substr(informationName.indexOf(value) + value.length) }}
              </span>
              <span v-else>{{ informationName }}</span>
            </template>
          </a-tree>

          <div class="drawer-bootom-button">
            <a-dropdown :trigger="['click']" placement="topCenter">
              <a-menu slot="overlay" class="much">
                <a-menu-item key="5" @click="expandAll">展开所有</a-menu-item>
                <a-menu-item key="6" @click="closeAll">合并所有</a-menu-item>
              </a-menu>
              <a-button class="searchBtn"> 树操作 <a-icon type="up" /> </a-button>
            </a-dropdown>
          </div>
        </div>
      </div>

      <div class="right-form-wrap bg-common-card f2 flex m-h-0" style="position: relative">
        <a-card v-if="selectedKeys.length > 0" :bordered="false" class="right-form-wrapper f1 flex column">
          <div v-if="currSelected.children.length == 0" class="add-btn cursor" @click="addEditHandle({})">新增</div>
          <div class="common-title flex align-center">
            <div class="icon"></div>
            <div class="context">特色功能</div>
          </div>

          <div v-if="currSelected.children.length == 0" class="item-group f1 flex column m-h-0">
            <div class="search-group">
              <div class="input-wrap">
                <div class="label">功能名称:</div>
                <div class="input-item">
                  <a-input
                    v-model="queryParam.industryFeaturesName"
                    :maxLength="30"
                    clearable
                    placeholder="请输入功能名称"
                  />
                </div>
              </div>
              <div class="btn-wrap">
                <a-button class="searchBtn" type="primary" @click="searchQuery()"> 搜索 </a-button>
                <a-button class="resetBtn" type="primary" @click="searchReset()"> 重置 </a-button>
              </div>
            </div>

            <div class="wrap f1 flex m-h-0" style="overflow: scroll">
              <a-table
                :columns="columns"
                :dataSource="dataSource"
                :pagination="ipagination"
                class="tableList"
                rowKey="id"
                @change="handleTableChange"
              >
                <template #appRouteUrl="records">
                  <a-tooltip placement="top">
                    <template slot="title">
                      <span>{{ records.appRouteUrl }} </span>
                    </template>
                    <span>{{ records.appRouteUrl }} </span>
                  </a-tooltip>
                </template>

                <template #webRouteUrl="records">
                  <a-tooltip placement="top">
                    <template slot="title">
                      <span>{{ records.webRouteUrl }} </span>
                    </template>
                    <span>{{ records.webRouteUrl }} </span>
                  </a-tooltip>
                </template>

                <template #miniRouteUrl="records">
                  <a-tooltip placement="top">
                    <template slot="title">
                      <span>{{ records.miniRouteUrl }} </span>
                    </template>
                    <span>{{ records.miniRouteUrl }} </span>
                  </a-tooltip>
                </template>

                <template #iconUrl="records">
                  <img :src="`${imgPrefix + records.iconUrl}`" alt="" style="width: 0.5rem; height: 0.5rem" />
                </template>
                <template v-slot:action="records">
                  <span class="operation deatil-color" @click="addEditHandle(records)">编辑 </span>

                  <!-- <span class="operation deatil-color" v-if="records.featuresStatus == 1" @click="showDrawer(records)"
                    >配置
                  </span> -->

                  <span class="operation warnColor" @click="showDelete(records)">删除 </span>
                </template>
              </a-table>
            </div>
          </div>
          <a-card v-else :bordered="false" class="f1 flex align-center justify-center">
            <a-empty>
              <span slot="description"> 只有最子集才可添加数据并查看！ </span>
            </a-empty>
          </a-card>
        </a-card>
        <a-card v-else :bordered="false" class="f1 flex align-center justify-center">
          <a-empty>
            <span slot="description"> 请先选择一个场所分类! </span>
          </a-empty>
        </a-card>
      </div>
    </div>

    <cus-drawer ref="cusDrawer" @loadTree="loadTree" @refresh="searchQuery()"></cus-drawer>
    <add-model ref="addModel" @loadTree="loadTree" @refresh="searchQuery"></add-model>
    <allMessage
      ref="allMessage"
      :publicVisible="publicVisible"
      @cancel="publicVisible = false"
      @tipMessage="tipMessage"
    ></allMessage>
  </div>
</template>

<script>
import topTitle from '@/components/topTitle'
import { getAction } from '@/api/manage'
import addModel from './modules/addModel'
import cusDrawer from './modules/drawer'
import allMessage from '@/components/allMessage'
import { findEnableDictItemsbyCode } from '@/api/api'
import { industryFeaturesDelete } from '@/api/industry'
export default {
  name: 'placeClassification',
  components: { topTitle, addModel, allMessage, cusDrawer },
  data() {
    return {
      content: [['特色功能']],
      loading: false,
      value: '', // tree search value
      dataList: [],
      currSelected: {},
      selectedKeys: [],
      checkedKeys: [],
      departTree: [],
      iExpandedKeys: [],
      checkStrictly: true,
      replaceFields: {
        key: 'id',
        title: 'informationName',
      },
      autoExpandParent: true,

      // 右边

      queryParam: {},
      dataSource: [],
      columns: [
        {
          title: '序号',
          align: 'center',
          width: 100,
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '功能名称',
          dataIndex: 'industryFeaturesName',
          ellipsis: true,
          align: 'center',
        },
        {
          title: 'ICON',
          align: 'center',
          scopedSlots: { customRender: 'iconUrl' },
        },
        {
          title: 'APP URL',
          align: 'center',
          ellipsis: true,
          scopedSlots: { customRender: 'appRouteUrl' },
        },
        {
          title: 'WEB URL',
          align: 'center',
          ellipsis: true,
          scopedSlots: { customRender: 'webRouteUrl' },
        },
        {
          title: '小程序 URL',
          align: 'center',
          ellipsis: true,
          scopedSlots: { customRender: 'miniRouteUrl' },
        },
        {
          title: '描述',
          align: 'center',
          dataIndex: 'memo',
        },
        {
          title: '操作',
          scopedSlots: { customRender: 'action' },
          align: 'center',
        },
      ],
      publicVisible: false,
      imgPrefix: '',
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['5', '10', '20'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
    }
  },
  mounted() {
    this.loadTree()
    this.getDict()
  },
  methods: {
    async loadTree() {
      this.loading = true
      let { result } = await getAction('/industry/information/tree')
      this.allTreeKeys = []
      this.departTree = result

      this.getAllKeys(result) // * 用于右下角树操作功能
      this.generateList(this.departTree) // * 用作搜索 书中包含关键字的方法
      this.loading = false
    },

    // * 清空
    onClearSelected() {
      this.selectedKeys = []
      this.checkedKeys = []
      this.currSelected = {}
      this.form.resetFields()
    },

    // * 用于右下角树操作功能
    getAllKeys(tree) {
      tree.forEach((item) => {
        if (item.id) this.allTreeKeys.push(item.id)
        if (item.children) {
          this.getAllKeys(item.children)
        }
      })
    },

    expandAll() {
      this.iExpandedKeys = this.allTreeKeys
    },

    closeAll() {
      this.iExpandedKeys = []
    },

    // * 树的筛选方法 开始
    onSearch() {
      const expanded = this.dataList
        .map((item) => {
          if (item.informationName.indexOf(this.value) > -1) {
            return this.getParentKey(item.id, this.departTree)
          }
          return null
        })
        .filter((item, i, self) => {
          if (item && self.indexOf(item) === i) {
            return item
          }
        })
      this.iExpandedKeys = expanded
      this.autoExpandParent = true
    },

    getParentKey(key, tree) {
      let parentKey
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i]
        if (node.children) {
          if (node.children.some((item) => item.id === key)) {
            parentKey = node.id
          } else if (this.getParentKey(key, node.children)) {
            parentKey = this.getParentKey(key, node.children)
          }
        }
      }
      return parentKey
    },

    generateList(tree) {
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i]
        const id = node.id
        const informationName = node.informationName
        this.dataList.push({
          id,
          informationName: informationName,
        })
        if (node.children) {
          this.generateList(node.children)
        }
      }
    },
    // * 树的筛选方法 结束

    // * 树方法
    onCheck(checkedKeys, info) {},

    onSelect(selectedKeys, info) {
      let record = info.node.dataRef
      console.log('onSelect-record', record)
      this.currSelected = record
      this.checkedKeys = [record.id] // ! 设置勾选
      this.selectedKeys = [record.id]

      this.setValuesToForm(record)
    },

    onExpand(expandedKeys) {
      this.iExpandedKeys = expandedKeys
      this.autoExpandParent = false
    },

    // * 触发onSelect事件时,为区域树右侧的form表单赋值
    setValuesToForm(record) {
      this.queryParam.industryInformationId = record.id
      this.searchQuery()
    },

    // * 右边 表单
    async searchQuery() {
      const { result } = await getAction('/industry/industry_features/page', this.queryParam)
      this.dataSource = result.records
      this.ipagination.total = result.total
    },

    handleTableChange(pagination) {
      this.ipagination = pagination
      this.searchQuery()
    },

    searchReset() {
      this.queryParam.industryFeaturesName = ''
      this.searchQuery()
    },

    addEditHandle(records) {
      records.industryInformationId = this.currSelected.id
      this.$refs.addModel.show(records)
    },

    // showDrawer(records) {
    //   if (records.industryFeaturesName == '设施信息') {
    //     this.$refs.cusDrawer.show('/hotel/device_config/list')
    //   } else {
    //     this.$message.warning('此功能暂未开发！')
    //   }
    // },

    showDelete(records) {
      this.publicVisible = true
      this.$refs.allMessage.show(records)
    },

    tipMessage(records) {
      industryFeaturesDelete({ id: records.id }).then((res) => {
        this.$message.success(res.message)
        this.publicVisible = false
        this.searchQuery()
      })
    },

    async getDict() {
      let { result } = await findEnableDictItemsbyCode({ code: 'static_server' })
      this.imgPrefix = result[0].value
    },
  },
}
</script>

<style lang="less" scoped>
.app-container {
  background: var(--theme-content-bg);
  padding-top: 0;

  .bg-common-card {
    background: var(--theme-container-bg);
  }

  .m-h-0 {
    min-height: 0;
  }

  .left-tree-wrap {
    position: relative;
    margin-right: 0.1rem;

    .btn-group {
      padding: 0.2rem 0 0 0.2rem;
      .btn-common {
        width: 1.2rem;
        height: 0.4rem;
        line-height: 0.4rem;
        text-align: center;
        background: #1388ff;
        border-radius: 0.04rem;
        font-size: 0.16rem;
        font-weight: bold;
        color: #0b3f73;
        cursor: pointer;
        &:nth-child(2) {
          margin-left: 0.2rem;
        }
      }
    }

    .drawer-bootom-button {
      position: absolute;
      right: 0.1rem;
      bottom: 0.1rem;
      border-radius: 0.04rem;
    }
  }

  .tree-wrap {
    padding: 0 0.2rem;
    overflow-y: scroll;
  }

  /deep/ .ant-card {
    background: var(--theme-container-bg);
    color: #1163b8;
  }

  /deep/ .ant-card-body {
    display: flex;
    flex-direction: column;
    flex: 1;
    min-height: 0;
  }

  .imageUpload {
    margin-bottom: 80px;
    /deep/.avatar-uploader {
      margin-left: 5px;
      > .ant-upload {
        width: 120px;
        height: 120px;
        background: var(--theme-container-bg);
        border: 1px solid var(--theme-input-border);
      }
    }

    /deep/.ant-upload-select-picture-card {
      width: 120px;
      height: 120px;
    }

    /deep/ .ant-upload-list-item {
      width: 120px;
      height: 120px;
    }

    .imgText {
      color: #1163b8;
      font-weight: 500;
    }

    .pictIcon {
      margin-bottom: 10px;
      width: 42px;
      height: 38px;
    }
  }

  .common-title {
    height: 0.6rem;
    line-height: 0.6rem;
    padding-left: 0.26rem;
    border-bottom: 2px solid var(--theme-input-border);
    // transform: translateY(-6px);
    .icon {
      width: 8px;
      height: 8px;
      background: #1388ff;
      border-radius: 50%;
      margin-right: 8px;
    }
    .context {
      font-size: 0.16rem;
      font-weight: 500;
      color: #1388ff;
    }
  }

  .common-item-wrap {
    overflow-y: scroll;
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-auto-flow: row;
  }
  .common-wrap {
    // width: 420px;
    height: 1.58rem;
    background: var(--theme-container-bg);
    border-radius: 2px;
    border: 0.01rem solid var(--theme-input-border);
    padding: 0 20px;
    margin: 16px;

    section {
      height: 50px;
      // padding-top: 15px;
      border-bottom: 1px solid #09427a;
      .left-content {
        font-size: 0.2rem;
        font-family: PingFang SC-Bold, PingFang SC;
        font-weight: bold;
        color: var(--theme-modal-label-value-color);
        .content {
          width: 234px;
          margin-left: 5px;
        }
      }
    }

    .bot {
      padding: 0 0 0 50px;
      font-size: 16px;
      font-weight: 500;
      color: #509eee;
      span {
        font-size: 16px;
        color: #1388ff;
      }

      .click {
        font-size: 14px;
        font-family: PingFang SC-Medium, PingFang SC;
        font-weight: 500;
        color: #47e829;
        cursor: pointer;
      }
    }
  }
}
</style>
